package com.topisv.tms.service.edi.wms;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.EdiOrderItemDao;
//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class EdiOSASourceService {
	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	
	@Autowired
	private EdiOrderDao ediOrderDao;
	@Autowired
	private EdiOrderItemDao ediOrderItemDao;
	
	@Transactional(readOnly = false)
	public void saveOrdenos(String customerCode,List<EdiOrder> ediOrders) throws Exception {
		if (ediOrders == null) {
			return;
		}
		for (int i = 0; i < ediOrders.size(); i++) {
			EdiOrder ediOrder = ediOrders.get(i);
			List<EdiOrder> orders = ediOrderDao.findByCustomerCodeAndCustomerOrdeno(customerCode,ediOrder.getOrdeno());
			EdiOrder tempEdiOrder = orders.isEmpty()? null : orders.get(0);
			if (tempEdiOrder != null) {// 删除重复的订单明细
				ediOrder.setId(tempEdiOrder.getId());
				ediOrderItemDao.deleteOrdeno(customerCode,ediOrder.getOrdeno());
			}
			List<EdiOrderItem> ediOrderItems = ediOrders.get(i).getSkulst();
			if ((ediOrderItems != null)) {
				if (ediOrderItems.size() == 1) {
					EdiOrderItem ediOrderItem = ediOrderItems.get(0);
					if (ediOrderItem.getQty() > 1) {
						ediOrder.setOrderType("multiple");
					} else {
						ediOrder.setOrderType("single");
					}
				} else {
					ediOrder.setOrderType("multiple");
				}
				ediOrderDao.save(ediOrder);// 保存订单状态
				for (int j = 0; j < ediOrderItems.size(); j++) {
					EdiOrderItem ediOrderItem = ediOrderItems.get(j);
					String ordeno = ediOrder.getOrdeno();
					ediOrderItem.setOrdeno(ordeno);
				}
				ediOrderItemDao.save(ediOrderItems);// 保存订单明细
			}
		}
	}

	
	
	@Transactional(readOnly = false)
	public void saveSkus(String customerCode,List<EdiGoodsSku> ediGoodsSkus) throws Exception{
		if (ediGoodsSkus != null) {
			for (int i = 0; i < ediGoodsSkus.size(); i++) {
				EdiGoodsSku ediGoodsSku = ediGoodsSkus.get(i);
				ediGoodsSku.setCustomerCode(customerCode);
				//代表是更新的商品信息记录
				EdiGoodsSku tempEdiGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(customerCode,ediGoodsSku.getSku());
				if (tempEdiGoodsSku != null) {
					ediGoodsSku.setId(tempEdiGoodsSku.getId());
				}
				String des = ediGoodsSku.getDes();
				if (des != null) {
					String[] dess = des.split(" ");
					if(dess.length==2){
						ediGoodsSku.setCol(dess[0]);
						ediGoodsSku.setSiz(dess[1]);
					}else if(dess.length==1){
						ediGoodsSku.setCol(dess[0]);
					}
				}
			}
			ediGoodsSkuDao.save(ediGoodsSkus);
		}
	}
	
}
